package com.qiahao.jwt;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定401返回值
 *
 * @author hackyo
 *         Created on 2017/12/9 20:10.
 */
@Component
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        JSONObject result = new JSONObject();
        JSONObject header = new JSONObject();
        if (authException instanceof BadCredentialsException) { /**身份认证未通过*/
            System.out.print("身份认证未通过");
            response.setStatus(401);
            try {
                header.put("errorcode", "401");
                header.put("errorinfo", "用户名或密码错误，请重新输入！");
                result.put("data", header);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {
            System.out.print("totken无效");
            response.setStatus(403);
            try {
                header.put("errorcode", "403");
                header.put("errorinfo", "无效的token");
                result.put("data", header);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        try {
            response.getWriter().write(result + "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
